<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <strong style="font-size: 20px;">
          工资记录
        </strong>
      </el-col>
      <el-col :span="20" align="center">
        <strong style="font-size: 16px;">
          账户余额:{{ balance }}
        </strong>
      </el-col>
    </el-row>
    <div style="width: 100%;">
      <el-tabs v-model="activeName" @tab-click="changeTab">
        <el-tab-pane label="历史" name="first">
          <el-row>
            <el-col :span="4" />
            <el-col :span="20" align="right">
              <span style="margin-right: .5em">
                <el-date-picker
                  v-model="search.beforeTime"
                  type="date"
                  placeholder="开始日期"
                  style="width: 150px;"
                  size="medium"
                  :editable="false"
                  value-format="yyyy-MM-dd"
                />
              </span>
              <span style="margin-right: .5em">
                <el-date-picker
                  v-model="search.afterTime"
                  type="date"
                  placeholder="结束日期"
                  style="width: 150px;"
                  size="medium"
                  :editable="false"
                  value-format="yyyy-MM-dd"
                />
              </span>
              <span style="margin-right: .5em">
                <el-select
                  v-model="search.staff"
                  filterable
                  clearable
                  placeholder="员工名称"
                  style="width: 150px;"
                  size="medium"
                >
                  <el-option v-for="item in staffs" :key="item.id" :label="item.name" :value="item.user" />
                </el-select>
              </span>

              <el-button
                size="medium"
                icon="el-icon-search"
                style="margin-right: 1em"
                circle
                @click="filterGenerate();dataProcessor()"
              />
            </el-col>
          </el-row>

          <el-row>
            <el-table
              v-loading="loading"
              :data="list"
              element-loading-text="加载中..."
              fit
              lazy
              stripe
              highlight-current-row
              style="width: 100%"
            >
              <el-table-column label="#" type="index" />
              <el-table-column label="员工">
                <template slot-scope="scope">
                  <span>{{ scope.row.attributes.name }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" />
              <el-table-column label="状态">
                <template slot-scope="scope">
                  <span>{{ statusOption[scope.row.status] }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="comment" label="备注" />
              <el-table-column prop="createdTime" label="创建时间" />
            </el-table>
          </el-row>

          <el-row>
            <div class="block">
              <el-pagination
                :current-page.sync="pager.page"
                :page-sizes="[20, 50, 100, 300]"
                :page-size="pager.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="paginator ? paginator.totalCount : 0"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="发放" name="second">
          <el-table
            :key="refreshStaff"
            v-loading="loadingStaff"
            :data="salaryData"
            element-loading-text="加载中..."
            fit
            lazy
            stripe
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column prop="name" label="员工" />
            <el-table-column prop="phone" label="电话" />
            <el-table-column label="金额(不填/填0不下发)">
              <template slot-scope="scope">
                <el-input v-model="scope.row.amount" type="number" />
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template slot-scope="scope">
                <el-input v-model="scope.row.comment" />
              </template>
            </el-table-column>
          </el-table>
          <div style="padding-top:10px">
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loadingStaff: false,
      list: [],
      refreshStaff: 0,
      store: 0,
      staffs: [],
      salaryData: [],
      activeName: 'first',
      paginator: [],
      pager: {
        page: 1,
        limit: 20
      },
      loading: false,

      search: {
        staff: null,
        beforeTime: null,
        afterTime: null,
        options: []
      },
      balance: 0,
      statusOption: {
        'pending': '等待中',
        'success': '成功',
        'failed': '失败'
      }
    }
  },
  created() {
    const store = localStorage.getItem('storeId')

    this.filterGenerate()
    this.dataProcessor()
    this.getBalance()

    if (store > 0) {
      this.store = store
      this.getStaffs()
    } else {
      this.$message.error('无效storeId，请退出重试')
    }
  },
  methods: {
    changeTab(tab, event) {
      if (tab.name === 'second') {
        this.salaryData = JSON.parse(JSON.stringify(this.staffs))
      } else {
        this.clearSearch()
        this.getBalance()
      }
    },
    clearSearch() {
      this.pager.page = 1
      this.search.staff = null
      this.search.beforeTime = null
      this.search.afterTime = null
      this.dataProcessor()
    },
    getBalance() {
      this.axios.get(`/api/balances`).then(res => {
        this.balance = res.data.amount
      })
    },
    getStaffs() {
      this.loadingStaff = true
      this.axios.get(`/store/${this.store}/staffs`, { params: {
        '@display': `{
              'id': 'entity.getId()',
              'name': 'entity.getName()',
              'phone': 'entity.getPhone()',
              'user': 'entity.getUser().getId()'
          }`,
        '@filter': 'entity.getEnabled() == true',
        'limit': 100000000
      }}).then((res) => {
        this.loadingStaff = false
        this.staffs = res.data
        this.salaryData = JSON.parse(JSON.stringify(res.data))
      })
    },
    submit() {
      const data = []
      for (var i of this.salaryData) {
        if (i.amount) {
          if (i.amount < 0) {
            this.$message.error('禁止填负数')
            return
          }
          if (i.comment) {
            data.push({ to: i.user, amount: i.amount, type: 'salary', attributes: { name: i.name }, comment: i.comment })
          } else {
            data.push({ to: i.user, amount: i.amount, type: 'salary', attributes: { name: i.name }})
          }
        }
      }
      if (data.length === 0) {
        this.$message.error('请为发放员工填写金额')
        return
      }
      console.log(data)

      const loading = this.$loading({
        lock: true,
        text: '数据交互中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios.post(`/api/transactions/send`, data).then(res => {
        this.$message.success('数据上送成功')
        this.activeName = 'first'
        this.clearSearch()
        this.getBalance()
      }).finally(() => {
        loading.close()
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item['amount']))
        if (index === 2) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0).toFixed(2)
          // sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    filterGenerate() {
      this.filter = {
        '@filter': 'entity.getType() == "salary"',
        '@display': `{
              'id': 'entity.getId()',
              'name': 'entity.getName()',
              'amount': 'entity.getAmount()',
              'status': 'entity.getStatus()',
              'comment': 'entity.getComment()',
              'userId': 'entity.getTo().getId()',
              'attributes': 'entity.getAttributes()',
              'createdTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")'
          }`,
        '@order': 'entity.id|DESC'
      }

      if (this.search.beforeTime) {
        const expression = `entity.getCreatedTime() >= datetime.get('${this.search.beforeTime} 00:00:00')`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && (${expression})`
        } else {
          this.filter['@filter'] = `(${expression})`
        }
      }
      if (this.search.afterTime) {
        const expression = `entity.getCreatedTime() < datetime.get('${this.search.afterTime} 23:59:59')`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && (${expression})`
        } else {
          this.filter['@filter'] = `(${expression})`
        }
      }
      if (this.search.staff) {
        const expression = `entity.getTo().getId() == '${this.search.staff}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && (${expression})`
        } else {
          this.filter['@filter'] = `(${expression})`
        }
      }
    },
    dataProcessor() {
      this.loading = true
      // table数据
      this.axios.get(`/api/transactions`, {
        params: Object.assign(
          {},
          this.filter,
          this.pager
        )
      }).then(res => {
        this.list = res.data
        this.loading = false
        this.paginator = res.paginator
      })
    },
    // Pager size changed
    handleSizeChange(val) {
      this.pager.limit = val
      this.dataProcessor()
    },

    // Pager page changed
    handleCurrentChange(val) {
      this.pager.page = val
      this.dataProcessor()
    }
  }
}
</script>
